<?php

// 公共助手函数
use think\Config;
use think\Url;

//插件菜单操作钩子
if (!function_exists('myadmin_menu')) {
    function myadmin_menu($v)
    {
        $backtrace = debug_backtrace()[0]['file'] ?? false;
        if ($backtrace) {
            $addnon = pathinfo($backtrace, PATHINFO_FILENAME);
            hook('myadmin_' . $v . '_menu', strtolower($addnon));
        }
        return true;
    }
}

//企业URL自动识别或添加参数
if (!function_exists('company_url')) {
    function company_url($appid = '')
    {
        if (COMPANY_URL) {
            return addon_urls(COMPANY_URL, ['companyappid' => $appid]);
        }
        return urls('index/index/index', ['companyappid' => $appid]);
    }
}

//插件URL自动识别或添加参数
if (!function_exists('addon_urls')) {
    function addon_urls($url, $vars = [], $suffix = true, $domain = false)
    {
        $vars = get_auto_vars($vars);
        return addon_url($url, $vars, $suffix, $domain);
    }
}

//URL自动识别或添加参数
if (!function_exists('urls')) {
    function urls($url = '', $vars = [], $suffix = true, $domain = false)
    {
        $vars = get_auto_vars($vars);
        return Url::build($url, $vars, $suffix, $domain);
    }
}
// 参数自动识别或添加
if (!function_exists('get_auto_vars')) {
    function get_auto_vars($vars = [])
    {
        if (is_string($vars)) {
            parse_str($vars, $vars);
        }
        if (PRIVATE_DOMAIN) {
            if (isset($vars['companyappid'])) {
                if (Config::get('company.identifier') == $vars['companyappid']) {
                    unset($vars['companyappid']);
                }
            } else {
                unset($vars['companyappid']);
            }
        } else {
            if (!isset($vars['companyappid'])) {
                $vars = array_merge($vars, ['companyappid' => Config::get('company.identifier', '')]);
            }
        }
        return $vars;
    }
}

/**
 * 获取企业插件配置
 * @param string $name 插件名称
 * @param int  $company_id 企业ID
 * @return array
 */
if (!function_exists('company_addons_config')) {
    function company_addons_config($company_id, $name)
    {
        return addons\myadmin\model\Addon::config($name, $company_id);
    }
}
